<?php
declare (strict_types = 1);

namespace app\wework\listener;
use think\facade\Db;
use app\wework\model\CallbackModel;
use app\wework\model\QyWechatApi;
use app\wework\model\user\autogroup\AutoPullGroupModel;


class BuffetPromotion
{
	public function handle($event){
        if($event["ChangeType"] == "add_external_contact"){
        	$this->promotion($event);
        }else if($event["ChangeType"] == "del_external_contact"){
        	$this->del($event);
        }else if($event["ChangeType"] == "del_follow_user"){
        	$this->del($event);
        }else if($event["ChangeType"] == "change_external_chat"){
        	$this->change($event);
        }
    }

	public function promotion($data){
        if(!array_key_exists("State",$data))return "不是该渠道";
        $promotion = Db::table('kt_wework_promotion')->where('state',$data['State'])->json(["staffs","tags","welcome_list"])->find();
        if(!$promotion)return "不是该渠道";
        $wid = $promotion["wid"];
        $staff = Db::table("kt_wework_staff")->where(["wid"=>$wid,"userid"=>$data['UserID']])->find();
        $customer = Db::table('kt_wework_customer')->where(['wid'=>$wid,'external_userid'=>$data['ExternalUserID'],'staff_id'=>$staff['id']])->find();
        if($promotion["is_tag"] == 1){
        	$addTag = $promotion['tags'];
            $tagParam = [
                'userid' => $data['UserID'],
                'external_userid' => $data['ExternalUserID'],
                'add_tag' => $addTag,
                'remove_tag'=> [],
            ];
            $editEtTagRes = QyWechatApi::editMarkTag($tagParam,$wid);
            if($editEtTagRes["errcode"] == 0){
                Db::table('kt_wework_customer')->where('id',$customer['id'])->json(['tags'])->save(['tags'=>$addTag]);
            }
        }
        $param["userid"] = $data['UserID'];
        $param["external_userid"] = $data['ExternalUserID'];
        if($promotion["is_describe"] == 1)$param["description"] = $promotion['describe'];
        if($promotion["is_bz"] == 1)$param["remark"] = $promotion['bz'];
		if($promotion["is_bz"] == 1 || $promotion["is_describe"] == 1){
			$upd = QyWechatApi::externalcontactRemark($param,$wid);
			if($upd["errcode"] == 0){
                Db::table('kt_wework_customer')->where('id',$customer['id'])->update(['remark'=>$promotion["remark"],'description'=>$promotion["description"]]);
            }
		}
		$is_size = Db::table("kt_wework_promotion_size")->where(["unionid"=>$customer["unionid"],"pid"=>$promotion["id"],"wid"=>$wid,"type"=>2,"status"=>1])->find();
		$size["wid"] = $wid;
		$size["pid"] = $promotion["id"];
		$size["type"] = 2;
		$size["status"] = 1;
		$size["headimgurl"] = $customer["avatar"];
		$size["nickname"] = $customer["name"];
		$size["unionid"] = $customer["unionid"];
		$size["ctime"] = date("Y-m-d H:i:s");
		$size["user_id"] = $staff["id"];
		if($is_size)$is_size = Db::table("kt_wework_promotion_size")->where(["unionid"=>$customer["unionid"],"pid"=>$promotion["id"],"wid"=>$wid,"type"=>2,"status"=>1])->update($size);
		if(!$is_size)$is_size = Db::table("kt_wework_promotion_size")->insertGetId($size);
		if($promotion["welcome_type"] == 1){
			$welcomeCode = $arr['WelcomeCode'];
			$msg = $promotion["welcome_text"];
			$msg = str_replace('[插入客户昵称]', $customer['name'], $msg);
            $msg = str_replace('<div>', '
', $msg);
            $msg = str_replace('&nbsp;', ' ', $msg);
            $msg = str_replace('<br>', '', $msg);
            $msg = str_replace('</div>', '', $msg);
            $msg = str_replace('amp;', '', $msg);
			$welcome['text'] = ['content'=>$msg];
			$attachments = $this->assembleOther($promotion['welcome_list'],$wid);
			if($attachments) $welcome['attachments'] = $attachments;
			$res = QyWechatApi::sendWelcomeMsg($wid, $welcome);
		}
    }

    //组装 换迎语附件 数据
    private function assembleOther($otherData,$wid){
        $data = [];
        foreach ($otherData as $other) {
            switch ($other['type']) {
                case '1':
                    $data[] = [
                        'msgtype'=>'image',
                        'image'=>[
                            'media_id' => QyWechatApi::mediaUpload($wid,$other['url'],'image')['media_id'],
                        ]
                    ];
                    break;
                case '2':
                    $data[] = [
                        'msgtype'=>'link',
                        'link'=>[
                            'title' => $other['title'],
                            'picurl' => $other['link_picurl'],
                            'desc' => $other['link_desc'],
                            'url' => $other['link_url'],
                        ]
                    ];
                    break;
                case '3':
                    $data[] = [
                        'msgtype'=>'miniprogram',
                        'miniprogram'=>[
                            'title' => $other['title'],
                            'pic_media_id' => QyWechatApi::mediaUpload($wid,$other['imageurl'],'image')['media_id'],
                            'appid' => $other['appid'],
                            'page' => $other['path'],
                        ]
                    ];
                    break;
            }
        }
        return $data;
    }

    public function del($arr){
    	$CorpID = $arr['ToUserName'];//企业微信CorpID
		$config = Db::table("kt_wework_config")->where(['corp_id'=>$CorpID])->find();
		$wid = $config["wid"];
		$staff = Db::table("kt_wework_staff")->where(["wid"=>$wid,"userid"=>$arr['UserID']])->find();
		$customer = Db::table('kt_wework_customer')->where(['wid'=>$wid,'external_userid'=>$data['ExternalUserID'],'staff_id'=>$staff['id']])->find();
		$sizes = Db::table("kt_wework_promotion_size")->where(["unionid"=>$customer["unionid"],"wid"=>$wid,"type"=>2,"status"=>1,"staff_id"=>$staff["id"]])->find();
		if($sizes->id){
			Db::table("kt_wework_promotion_size")->where(["unionid"=>$customer["unionid"],"wid"=>$wid,"type"=>2,"status"=>1,"staff_id"=>$staff["id"]])->update(["is_qun"=>1]);
			$size_one = (new Model("qy_promotion_size"))->where(["unionid"=>$customer["unionid"],"pid"=>$sizes["pid"],"wid"=>$wid,"type"=>3,"status"=>1,"staff_id"=>$staff["id"]])->find();
			if(!$size_one){
				$size["wid"] = $wid;
				$size["pid"] = $sizes["pid"];
				$size["type"] = 3;
				$size["status"] = 1;
				$size["headimgurl"] = $customer["avatar"];
				$size["nickname"] = $customer["name"];
				$size["unionid"] = $customer["unionid"];
				$size["ctime"] = date("Y-m-d H:i:s");
				$size["staff_id"] = $staff["id"];
				Db::table("kt_wework_promotion_size")->insertGetId($size);
			}
		}
    }

    public function change($arr){
    	if($arr['ChangeType'] != 'update')return '不是该渠道';
    	$CorpID = $arr['ToUserName'];
		$config = Db::table("kt_wework_config")->where(['corp_id'=>$CorpID])->find();
		$wid = $config["wid"];
    	if($arr["UpdateDetail"] == "add_member"){
    		$size = Db::table("kt_wework_promotion_size")->where(["unionid"=>$arr["new_member"][0]["unionid"],"wid"=>$wid,"type"=>2,"group_id"=>$arr["ChatId"]])->find();
			if(!$size)return "不是该渠道";
			Db::table("kt_wework_promotion_size")->where(["unionid"=>$arr["new_member"][0]["unionid"],"wid"=>$wid,"type"=>2,"group_id"=>$arr["ChatId"]])->update(["is_qun"=>1,"type"=>2,"status"=>2]);
		}else if($arr["UpdateDetail"] == "del_member"){
			//获取群详情
			$info = QyWechatApi::getExternalGroupchatDetail($arr['ChatId'],$wid);
			$member_list = $info['group_chat']["member_list"];
			$unionids = array_column($member_list, "unionid");
			$size_list = Db::table("kt_wework_promotion_size")->where(["wid"=>$wid,"type"=>2,"status"=>2,"group_id"=>$arr['ChatId'],"is_qun"=>1])->column("unionid");
			foreach ($size_list as $value) {
				if(!in_array($value, $unionids)){
					$size = Db::table("kt_wework_promotion_size")->where(["wid"=>$wid,"type"=>2,"status"=>2,"group_id"=>$arr['ChatId'],"is_qun"=>1,"unionid"=>$value])->find();
					Db::table("kt_wework_promotion_size")->where(["wid"=>$wid,"type"=>2,"status"=>2,"group_id"=>$arr['ChatId'],"is_qun"=>1,"unionid"=>$value])->update(["is_qun"=>0]);
					$sizes["wid"] = $wid;
					$sizes["pid"] = $size["pid"];
					$sizes["type"] = 3;
					$sizes["status"] = 2;
					$sizes["user_id"] = $size["user_id"];
					$sizes["headimgurl"] = $size["headimgurl"];
					$sizes["nickname"] = $size["nickname"];
					$sizes["unionid"] = $value;
					$sizes["ctime"] = date("Y-m-d H:i:s");
					$sizes["group_id"] = $arr['ChatId'];
					$sizes["is_qun"] = 0;
					Db::table("kt_wework_promotion_size")->insertGetId($sizes);
				}
			}
		}
    }

}